// import website from '@/config/website'
// import { getToken } from '@/util/auth'

function unicodeToChar(text) {
  if (!text)
    return ''

  return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
    return String.fromCharCode(parseInt(p1, 16))
  })
}

const handleStream = (response, onData, onCompleted, onMessageEnd, onThought) => {
  const reader = response.body?.getReader()
  const decoder = new TextDecoder('utf-8')
  let buffer = ''
  let bufferObj = {}
  let isFirstMessage = true
  function read() {
    let hasError = false
    reader?.read().then((result) => {
      if (result.done) {
        onCompleted && onCompleted()
        return
      }
      buffer += decoder.decode(result.value, { stream: true })
      const lines = buffer.split('\n')
      try {
        lines.forEach((message) => {
          if (message.startsWith('data:')) { // check if it starts with data:
            try {
              bufferObj = JSON.parse(message.substring(5))// remove data: and parse as json
            }
            catch (e) {
              // mute handle message cut off
              onData('', isFirstMessage, {
                conversationId: bufferObj?.conversation_id,
                messageId: bufferObj?.message_id,
              })
              return
            }
            if (bufferObj.status === 400 || !bufferObj.event) {
              onData('', false, {
                conversationId: undefined,
                messageId: '',
                errorMessage: bufferObj?.message,
                errorCode: bufferObj?.code,
              })
              hasError = true
              onCompleted?.(true, bufferObj?.message)
              return
            }
            if (bufferObj.event === 'message' || bufferObj.event === 'agent_message') {
              // can not use format here. Because message is splitted.
              onData(unicodeToChar(bufferObj.answer), isFirstMessage, {
                conversationId: bufferObj.conversation_id,
                taskId: bufferObj.task_id,
                messageId: bufferObj.id,
              })
              isFirstMessage = false
            }
            else if (bufferObj.event === 'agent_thought') {
              onThought?.(bufferObj)
            }
            // else if (bufferObj.event === 'message_file') {
            //   onFile?.(bufferObj as VisionFile)
            // }
            else if (bufferObj.event === 'message_end') {
              onMessageEnd?.(bufferObj, )
            }
            // else if (bufferObj.event === 'message_replace') {
            //   onMessageReplace?.(bufferObj as MessageReplace)
            // }
            // else if (bufferObj.event === 'workflow_started') {
            //   onWorkflowStarted?.(bufferObj as WorkflowStartedResponse)
            // }
            // else if (bufferObj.event === 'workflow_finished') {
            //   onWorkflowFinished?.(bufferObj as WorkflowFinishedResponse)
            // }
            // else if (bufferObj.event === 'node_started') {
            //   onNodeStarted?.(bufferObj as NodeStartedResponse)
            // }
            // else if (bufferObj.event === 'node_finished') {
            //   onNodeFinished?.(bufferObj as NodeFinishedResponse)
            // }
            // else if (bufferObj.event === 'iteration_started') {
            //   onIterationStart?.(bufferObj as IterationStartedResponse)
            // }
            // else if (bufferObj.event === 'iteration_next') {
            //   onIterationNext?.(bufferObj as IterationNextResponse)
            // }
            // else if (bufferObj.event === 'iteration_completed') {
            //   onIterationFinish?.(bufferObj as IterationFinishedResponse)
            // }
            // else if (bufferObj.event === 'parallel_branch_started') {
            //   onParallelBranchStarted?.(bufferObj as ParallelBranchStartedResponse)
            // }
            // else if (bufferObj.event === 'parallel_branch_finished') {
            //   onParallelBranchFinished?.(bufferObj as ParallelBranchFinishedResponse)
            // }
            // else if (bufferObj.event === 'text_chunk') {
            //   onTextChunk?.(bufferObj as TextChunkResponse)
            // }
            // else if (bufferObj.event === 'text_replace') {
            //   onTextReplace?.(bufferObj as TextReplaceResponse)
            // }
            // else if (bufferObj.event === 'tts_message') {
            //   onTTSChunk?.(bufferObj.message_id, bufferObj.audio, bufferObj.audio_type)
            // }
            // else if (bufferObj.event === 'tts_message_end') {
            //   onTTSEnd?.(bufferObj.message_id, bufferObj.audio)
            // }
          }
        })
        buffer = lines[lines.length - 1]
      }
      catch (e) {
        onData('', false, {
          conversationId: undefined,
          messageId: '',
          errorMessage: `${e}`,
        })
        hasError = true
        onCompleted?.(true)
        return
      }
      if (!hasError)
        read()
    })
  }
  read();
};

const myFetch = (fetchOptions, otherOptions) => {
  // const { onData, onCompleted, onMessageEnd, onThought, onError } = otherOptions;
  const data = {
    "response_mode": "streaming",
    // "conversation_id": "029f2f36-7e92-4420-8d06-017e9baf1e7d",
    "files": [],
    "query": '',
    "inputs": {},
    "parent_message_id": 'be154d22-2f03-4d94-8378-c3a997d6eca9',
    ...fetchOptions,
    // "response_mode": "streaming",
    //   "conversation_id": "785bf886-3316-41e6-8bbe-241ec6b0dbeb",
    //   "files": [],
    //   "query": "财经新闻",
    //   "inputs": {},
    //   "parent_message_id": "4d2a22e3-ffeb-4f56-9338-ac89f2dddcdc"
  };
  const headers = {
    // [website.tokenHeader]: 'bearer ' + getToken(),
    'Content-Type': 'application/json',
    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI2OGNmNjVjZS1kNDAzLTQ0ZDAtYTM5NC1hMDBlYjkwNDdmNjQiLCJzdWIiOiJXZWIgQVBJIFBhc3Nwb3J0IiwiYXBwX2lkIjoiNjhjZjY1Y2UtZDQwMy00NGQwLWEzOTQtYTAwZWI5MDQ3ZjY0IiwiYXBwX2NvZGUiOiJDbThtdWQ3aDNHWVhTZ0xmIiwiZW5kX3VzZXJfaWQiOiI5NDc3ZDRjZi03MzVjLTQzMDMtODY0YS0zZDBlZmIzNjEyMGUifQ.7OKqzyo4Sh98HR1UeF7MZ62NJ4WQRDvU4Ofm7G-4rQA'
  };
  const abortController = new AbortController()
  const options = {
    method: 'POST',
    signal: abortController.signal,
    headers,
    body: JSON.stringify(data),
  };
  // const url = 'http://aics-pro-api.aigc.paas.test/api/chat-messages';
  const url = '/suggest/api/chat-messages'
  // const url = '/api/planner-workbench/aiHelper/chat-messages';
  
  return fetch(url, options)
}

export default myFetch;
